import datetime
import json
import time


class TimeUse(object):

    def __init__(self):
        self.start_time = time.time()
        self.up_time = 0  # 上次记录时间
        self.msg = ''
        self.all_msg = {}
        self.all_time = 0

    def print_time(self, msg):
        t_now = time.time()
        self.msg = msg
        # print(self.msg + " all：" + str(time.time() - self.start_time))
        # print(self.msg + " up_time：" + str(time.time() - self.up_time))
        self.all_time = time.time() - self.start_time
        self.all_msg.update({
            self.msg: {
                "all": str(self.all_time),
                "up_time": str(time.time() - self.up_time)
            }
        })
        self.up_time = t_now
        return t_now

    def set_time(self):
        """
        网络请求耗时
        :return:
        """
        pass

    async def write_nosql(self):
        from app_main import request_ctx_var
        from app_main import app
        from apps.sql_app.mmongodb import Coll
        request = request_ctx_var.get()
        m = dict()
        if request:
            m["client_ip"] = str(request.client.host)
            m["request_url"] = str(request.url)
            m["request_body"] = str(request.state.mbody)
            m["client_ip"] = str(request.client.host)
        m["ip_port"] = app.state.ip + ":" + str(app.state.port)
        m["write_time"] = str(datetime.datetime.now())
        m["time_log"] = json.dumps(self.all_msg, ensure_ascii=False)
        m["all_time"] = json.dumps(self.all_time, ensure_ascii=False)
        mongonn = Coll.get_request_time()
        # await mongonn.insert_one(m)
        from apps.crawler_platform.util.nosqlhelper import NOSQLHelper
        result = await NOSQLHelper.insert_one(mongonn, m,
                                              list_exception_name=["DocumentTooLarge"])
